import yaml
import logging
import os
import time

localtime = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
DATA_PATH = 'D:\PycharmProjects\HogwartsSDET21\pytest_practice\calculator\datas\data.yaml'
LOG_PATH = f'D:\PycharmProjects\HogwartsSDET21\pytest_practice\calculator\logs\{localtime}.log'


class YamlUtil(object):
    path = None
    data = None

    def __init__(self, path):
        self.path = path

    def read_test_data_by_yaml(self, key=None):
        with open(self.path, encoding='utf-8') as f:
            content = f.read()
            self.data = yaml.safe_load(content)
            f.close()
        if key is not None:
            for i in key.split('.'):
                try:
                    if i in self.data:
                        self.data = self.data[i]
                except Exception as e:
                    print(e)
        return self.data

    @staticmethod
    def read_test_data_by_dict(data, key=None):
        if key is not None:
            for i in key.split('.'):
                try:
                    if i in data:
                        data = data[i]
                except Exception as e:
                    print(e)
        return data


class PyTestLog:
    """
    日志功能
    """
    test_logger = None
    test_logger_stream_handler = None
    test_logger_file_handler = None
    test_logger_formatter = None

    def __init__(self, name, log_path):

        log_path = os.path.abspath(log_path)
        if os.path.isfile(log_path):
            pass
        else:
            with open(log_path, 'x') as f:
                f.close()
        self.test_logger = logging.getLogger(name)
        self.test_logger.setLevel(logging.DEBUG)
        self.test_logger_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        self.test_logger_stream_handler = logging.StreamHandler()
        self.test_logger_file_handler = logging.FileHandler(log_path, encoding='utf-8')
        self.test_logger_stream_handler.setLevel(logging.DEBUG)
        self.test_logger_file_handler.setLevel(logging.DEBUG)
        self.test_logger_stream_handler.setFormatter(self.test_logger_formatter)
        self.test_logger_file_handler.setFormatter(self.test_logger_formatter)
        self.test_logger.addHandler(self.test_logger_stream_handler)
        self.test_logger.addHandler(self.test_logger_file_handler)

    def log_debug(self, msg):
        self.test_logger.debug(msg)

    def log_info(self, msg):
        self.test_logger.info(msg)

    def log_warning(self, msg):
        self.test_logger.warning(msg)

    def log_error(self, msg):
        self.test_logger.error(msg)
